package utilVnc

import (
	"bufio"
	"fmt"
	"gitee.com/hilaoyu/go-basic-utils/utilVnc/types"
	"net"
	"time"
)

// The VncConn type holds client connection information

// NewVncConn creates new client conn using config
func NewVncConn(address string, handlers []types.Handler, timeout time.Duration, listeners ...*types.MessageListener) (*types.VncConn, error) {
	c, err := net.DialTimeout("tcp", address, timeout)
	if err != nil {
		return nil, fmt.Errorf("connection to VNC host failed: %v", err)
	}

	err = c.(*net.TCPConn).SetKeepAlive(true)
	if err != nil {
		return nil, fmt.Errorf("enable vnc backend connection keepalive failed:%v", err)
	}

	err = c.(*net.TCPConn).SetKeepAlivePeriod(30 * time.Second)
	if err != nil {
		return nil, fmt.Errorf("set vnc backend connection keepalive period failed:%v", err)
	}

	conn := types.VncConn{
		C:  c,
		Br: bufio.NewReader(c),
		Bw: bufio.NewWriter(c),
	}

	for _, h := range handlers {
		if err = h.Handle(&conn); nil != err {
			conn.Close()
			return nil, err
		}
	}
	conn.SetListeners(listeners)
	conn.RunListeners()

	return &conn, nil
}
